package com.cheil.publish.web;

import com.alibaba.fastjson2.JSON;
import com.cheil.publish.service.ai.DashscopeImageGenerationMetadata;
import com.cheil.publish.service.ai.DashscopeImageOptions;
import com.cheil.publish.service.ai.DashscopeImageOptions.Builder;
import com.cheil.publish.service.ai.DashscopeService;
import com.cheil.publish.service.data.ChatsDto;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.ai.image.ImageGeneration;
import org.springframework.ai.image.ImageResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * 图像生成控制器
 */
@Tag(name = "图像生成")
@RestController
@RequestMapping("/api/image")
@AllArgsConstructor
@Log4j2
public class ImageController {

    private final DashscopeService dashscopeService;

    /**
     * 根据文本生成图像
     *
     * @param prompt 图像描述文本
     * @return 图像URL列表
     */
    @PostMapping("/generate")
    public ResponseEntity<List<String>> generateImage(@RequestParam String prompt) {
        try {
            ImageResponse response = dashscopeService.generateImage(prompt);
            List<String> imageUrls = response.getResults().stream()
                    .map(imageGeneration -> imageGeneration.getOutput().getUrl())
                    .collect(Collectors.toList());

            return ResponseEntity.ok(imageUrls);
        } catch (Exception e) {
            log.error("图像生成失败: ", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 根据文本和选项生成图像
     *
     * @param prompt 图像描述文本
     * @param model 模型名称 (可选)
     * @param n 生成图像数量 (可选)
     * @param width 图像宽度 (可选)
     * @param height 图像高度 (可选)
     * @param negativePrompt 反向提示词 (可选)
     * @param promptExtend 是否开启prompt智能改写 (可选)
     * @param watermark 是否添加水印 (可选)
     * @param seed 随机种子 (可选)
     * @return 图像URL列表
     */
    @PostMapping("/generate/advanced")
    public ResponseEntity<List<String>> generateImageAdvanced(
            @RequestParam String prompt,
            @RequestParam(required = false) String model,
            @RequestParam(required = false) Integer n,
            @RequestParam(required = false) Integer width,
            @RequestParam(required = false) Integer height,
            @RequestParam(required = false) String negativePrompt,
            @RequestParam(required = false) Boolean promptExtend,
            @RequestParam(required = false) Boolean watermark,
            @RequestParam(required = false) String seed) {

        try {
            Builder builder = DashscopeImageOptions.builder();

            if (model != null) {
                builder.model(model);
            }

            if (n != null) {
                builder.n(n);
            }

            if (width != null && height != null) {
                builder.widthHeight(width, height);
            }

            if (negativePrompt != null) {
                builder.negativePrompt(negativePrompt);
            }

            if (promptExtend != null) {
                builder.promptExtend(promptExtend);
            }

            if (watermark != null) {
                builder.watermark(watermark);
            }

            if (seed != null) {
                builder.seed(seed);
            }

            DashscopeImageOptions options = builder.build();
            ImageResponse response = dashscopeService.generateImage(prompt, options);

            List<String> imageUrls = response.getResults().stream()
                    .map(imageGeneration -> imageGeneration.getOutput().getUrl())
                    .collect(Collectors.toList());

            return ResponseEntity.ok(imageUrls);
        } catch (Exception e) {
            log.error("图像生成失败: ", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    @PostMapping("/auto/publish")
    public Flux<ChatsDto> publish(@RequestParam String message) {

        ChatsDto chat = dashscopeService.chat(message);
        ImageResponse response = dashscopeService.generateImage(chat.content());
        log.info("chat {}", JSON.toJSONString(chat));
        log.info("image {}", JSON.toJSONString(response));
        ImageGeneration result = response.getResult();
        DashscopeImageGenerationMetadata metadata = (DashscopeImageGenerationMetadata) result.getMetadata();
        ChatsDto chatsDto = new ChatsDto(
                chat.title(),
                chat.content(),
                result.getOutput().getUrl(),
                metadata.getRevisedPrompt(),
                chat.tags()
        );
        return Flux.just(chatsDto);
    }
}